<?php
include_once __DIR__.'/class/XMLNode.php';
include_once __DIR__.'/class/XMLParser.php';
include_once __DIR__.'/class/XMLParserException.php';

/** 
 * The controller for requests
 * 
 * @author Thuan Chau <thuanchau2020@gmail.com>
 * @package Controller
 */
class Controller {
	/**
	 * @const string name of session variable that used to store the xml data.
	 */
	const UPLOADED_XML_DATA					= 'xml_data';

	/**
	 * The class constructor
	 * 
	 * @access public
	 */
	public function __construct() {}

	/**
	 * This method running controller
	 * 
	 * @access public
	 */
	public function run() {
		// check if the action is 'ajax_call'
		if (isset($_REQUEST['ajax_call'])) {
			$this->getXMLContentByAjax($_REQUEST['path']);
		}
		// if not, display index page			
		else {
			$this->index();
		}
	}

	/**
	 * The method is default action of controller, for display default page
	 * 
	 * @uses $_SESSION[self::UPLOADED_XML_DATA] a session variable that store xml data	 
	 * @access private
	 */
	private function index() {
		$error_message = '';

		// check if the action is 'action_upload'
		if (!empty($_REQUEST['action_upload'])) {
			// get the name of upload file
			if (!empty($_FILES['xml_file']['tmp_name'])) {
				$xml_file_name = $_FILES['xml_file']['tmp_name'];
			}

			// init xml parser
			$xml_parser = new XMLParser();

			try {
				// try to parse xml file to object XMLNode
				$xml_data = $xml_parser->parse($xml_file_name);
				
				// store object data to session
				$_SESSION[self::UPLOADED_XML_DATA] = serialize($xml_data);
			} catch(XMLParserException $xml_parser_error) {
				// get error message
				$error_message = "Error: " . $xml_parser_error->getMessage();
			}
		}

		include_once 'loadXML.html';
	}

	/**
	 * Get json data of a node
	 * 
	 * @uses $_SESSION[self::UPLOADED_XML_DATA] a session variable that store xml data
	 * @param string $path [optional] path of the node
	 * @return string json data of the node.
	 * @access private
	 */
	private function getXMLContentByAjax($path = null) {
		// check if the xml data has been stored before
		if ($_SESSION[self::UPLOADED_XML_DATA]) {
			try
			{
				// get object data from session
				$xml_data = unserialize($_SESSION[self::UPLOADED_XML_DATA]);

				// get the current node from path
				$xml_node = $xml_data->getNodeByPath($path);

				// return json form of current node
				echo $xml_node->toJSON();
			} catch(XMLParserException $xml_parser_error) {
				// if error happen, return empty string
			}
		}
	}
}

?>